package br.com.insight.consultoria.integracao.dao.genericdao;

import java.io.Serializable;
import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.springframework.dao.support.DataAccessUtils;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import br.com.insight.consultoria.erro.exception.InsightException;

public class GenericDAO extends HibernateDaoSupport {
	
	protected Object getEntityById(Class clazz,Serializable id){
		return getHibernateTemplate().get(clazz, id);
	}
	
	protected void saveEntity(Object entity) throws InsightException{
		getHibernateTemplate().persist(entity);
	}
	
	protected void saveOrUpdateEntity(Object entity) throws InsightException{
		getHibernateTemplate().saveOrUpdate(entity);
	}
	
	protected void updateEntity(Object entity) throws InsightException{
		getHibernateTemplate().update(entity);
	}
	
	protected void deleteEntity(Object entity) throws InsightException{
		getHibernateTemplate().delete(entity);
	}
	
	protected void deleteEntityById(Class clazz, Serializable id) throws InsightException{
		Object entity = getEntityById(clazz, id);
		if (entity != null) {
		deleteEntity(entity);
		}
	}
	
	protected List findAll(Class clazz) throws InsightException{
		return getHibernateTemplate().loadAll(clazz);
	}
	
	protected List findAll(Class clazz, String orderBy) throws InsightException{
		return getHibernateTemplate().findByCriteria(
		DetachedCriteria.forClass(clazz).addOrder(Order.asc(orderBy)));
	}
	
	protected List findFiltered(Class clazz, String property, Object filter)throws InsightException {
		
		return getHibernateTemplate().findByCriteria(
		DetachedCriteria.forClass(clazz).add(
		org.hibernate.criterion.Expression.eq(property, filter)));
		
	}
	
	protected List findFiltered(Class clazz, String property,
		Object filter, String orderBy) throws InsightException{
		return getHibernateTemplate().findByCriteria(
		DetachedCriteria.forClass(clazz).add(
		org.hibernate.criterion.Expression.eq(property, filter)).addOrder(
		Order.asc(orderBy)));
	}
	
	protected Object findUniqueFiltered(Class clazz, String property,
			Object filter) throws InsightException{
			return DataAccessUtils.requiredUniqueResult(getHibernateTemplate()
			.findByCriteria(
			DetachedCriteria.forClass(clazz).add(
			org.hibernate.criterion.Expression.eq(property, filter))));
	}
	
	protected Object findUniqueFiltered(Class clazz, String property,
			Object filter, String orderBy)throws InsightException {
		
			return DataAccessUtils.requiredUniqueResult(getHibernateTemplate()
			.findByCriteria(
			DetachedCriteria.forClass(clazz).add(
			org.hibernate.criterion.Expression.eq(property, filter)).addOrder(
			Order.asc(orderBy))));
	}
	
}
